/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.progin.drop.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author HP
 */
public class Util {

    public static String getFileChecksum(File file) {
        if (file.exists() && file.isFile()) {
            FileInputStream fis;
            try {
                fis = new FileInputStream(file);
                byte[] b = new byte[(int)file.length()];
                fis.read(b);
                fis.close();

                return convertToHex(getHash(b));
            } catch (IOException ex) {
                Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
                return null;
            }

        }
        else
            return null;
    }

    public static byte[] getHash(byte[] content) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("MD5");
            byte[] bs = md.digest(content);
            return bs;
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    public static String convertToHex(byte[] data) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                if ((0 <= halfbyte) && (halfbyte <= 9))
                    buf.append((char) ('0' + halfbyte));
                else
                    buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[i] & 0x0F;
            } while(two_halfs++ < 1);
        }
        return buf.toString();
    }
}
